set auto_path [concat [pwd]/../../pkg/tkMD $auto_path ]

package require tkMD 1.1
namespace import Data::*

if { [llength $argv] == 1 } {
  set protocol [lindex $argv 0]
  if ![file exists $protocol.tcl] { error "Do not have $protocol.tcl under current folder!"}
} else {
   puts "Usage example: whamrun.tcl protol1"
   exit
}

set nreplica 4
set wham_variable com
source $protocol.tcl

# Concatenate the wham.dat from different replication.  
if { $nreplica == 1 } {
set result [batch_cat [pwd]/$protocol wham.dat $protocol/@pept/type_@type/com_@com/wham.dat --combine none --save [pwd]/data/$protocol --calc force ]
} else {
set result [batch_cat [pwd]/$protocol wham.dat $protocol/@pept/type_@type/com_@com/run@i/wham.dat --combine i --save [pwd]/data/$protocol --calc force]
}

# Generate metafile for wham analysis.
set keys [dict keys [lindex $result 0 ]]
set keys [lremove $keys [list fname force $wham_variable]]
foreach r $result {
    set access_key ""
    set filename_ext ""
    foreach key $keys { append access_key "$key=[dict get $r $key]," ; append filename_ext [dict get $r $key]. }
    if ![info exists metafile($access_key)] {
        set metapath($access_key) $protocol.${filename_ext}meta
        set enerpath($access_key) $protocol.${filename_ext}ener
        set metafile($access_key) [open $protocol.${filename_ext}meta w]
        puts $metafile($access_key) "## path win force"
        puts $metafile($access_key) "[dict get $r fname] [dict get $r $wham_variable] [expr [dict get $r force]*2] "
    } else {
        puts $metafile($access_key) "[dict get $r fname] [dict get $r $wham_variable] [expr [dict get $r force]*2] "
    }
}


foreach key [array names metafile] {
close $metafile($key)
puts "Calculating wham from data $metapath($key) ..."
exec wham $wlo $whi $nbins 0.001 $temp  0 $metapath($key) $enerpath($key) 50 1223
puts "Saving into file $enerpath($key) ..."
}
